package com.file.parser;

import com.file.bo.IIT;
import com.file.bo.IITTran;
import com.file.constant.EfpConstants;
import com.file.constant.ErrorCode;
import com.file.bo.ResponseData;
import com.file.parser.traprange.PDFTableExtractor;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class IITPdfParser extends BaseDecryptPdfParser {

	public ResponseData<String> parseIITPdfToJson(String filePath, String pdfPassword) {
		log.info("parseIITPdfToJson started, filePath:{}, pdfPassword:{}", filePath, pdfPassword);
		String json = null;

		try {
			IIT iit = parseIITPdf(filePath, pdfPassword);
			json = JsonUtils.convertObjectToJson(iit);
		} catch (Exception e) {
			log.error("[OnError]parseIITPdfToJson failed, filePath:{}, pdfPassword:{}", filePath, pdfPassword, e);
			return new ResponseData<String>(json, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
					ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
		}

		log.info("parseIITPdfToJson completed, filePath:{}, pdfPassword:{}", filePath, pdfPassword);
		return new ResponseData<String>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
	}
	


	public IIT parseIITPdf(String filePath, String pdfPassword) {
		IIT iit = parseIITHeader(filePath, pdfPassword);

		List<IITTran> iitTrans = new ArrayList<>();
		iitTrans = parseIITTrans(filePath, pdfPassword);


		iit.setIitTrans(iitTrans);
		return iit;
	}

	public IIT parseIITHeader(String filePath, String pdfPassword) {
		IIT iit = new IIT();
		String pdfHeaderText = parsePdfHeaderText(filePath, pdfPassword);
		String recordPeriod = pdfHeaderText
				.substring(pdfHeaderText.indexOf("记 录 期 间 :") + 9, pdfHeaderText.indexOf("纳 税 ⼈ 名 称 : ")).trim();
		String taxpayerName = pdfHeaderText
				.substring(pdfHeaderText.indexOf("纳 税 ⼈ 名 称 :") + 11, pdfHeaderText.indexOf("纳税⼈识别号:")).trim();
		String taxpayerIdNo = pdfHeaderText
				.substring(pdfHeaderText.indexOf("纳税⼈识别号:") + 7, pdfHeaderText.indexOf("⾝份证件类型:")).trim();
		String IdCardType = pdfHeaderText
				.substring(pdfHeaderText.indexOf("⾝份证件类型:") + 7, pdfHeaderText.indexOf("⾝份证件号码:")).trim();
		String idNo = pdfHeaderText.substring(pdfHeaderText.indexOf("⾝份证件号码:") + 7, pdfHeaderText.indexOf("⾦额单位:"))
				.trim();
		String amountUnit = pdfHeaderText.substring(pdfHeaderText.indexOf("⾦额单位:") + 5, pdfHeaderText.indexOf("申报⽇期"))
				.trim();
		String issueDate = pdfHeaderText
				.substring(pdfHeaderText.indexOf("开具时间：") + 5, pdfHeaderText.indexOf("本凭证不作为纳税⼈记账")).trim();

		iit.setRecordPeriod(recordPeriod);
		iit.setTaxpayerName(taxpayerName);
		iit.setTaxpayerIdNo(taxpayerIdNo);
		iit.setIdCardType(IdCardType);
		iit.setIdNo(idNo);
		iit.setAmountUnit(amountUnit);
		iit.setIssueDate(issueDate);

		return iit;
	}

	public String parseTransToText(String filePath, String pdfPassword) {
		PDFTableExtractor extractor = (new PDFTableExtractor()).setSource(filePath, pdfPassword);
		int pdfPageNumber = getPdfPageNumber(filePath, pdfPassword);

		for (int k = 0; k < pdfPageNumber; k++) {
			// 对第一页处理
			int[] skipLinesIndexes1;
			if (k == 0) {
				//第一页多一行，单位，其它页少一行这个
				skipLinesIndexes1 = new int[EfpConstants.IIT_HEADER_LINE_NUMBER];
				for (int i = 0; i < EfpConstants.IIT_HEADER_LINE_NUMBER; i++) {
					skipLinesIndexes1[i] = i;
				}
			} else {
				skipLinesIndexes1 = new int[EfpConstants.IIT_HEADER_LINE_NUMBER - 1];
				for (int i = 0; i < EfpConstants.IIT_HEADER_LINE_NUMBER - 1; i++) {
					skipLinesIndexes1[i] = i;
				}
			}
			extractor.exceptLine(k, skipLinesIndexes1);

			int[] skipLinesIndexes2 = new int[EfpConstants.IIT_FOOTER_LINE_NUMBER];
			for (int j = 0; j < EfpConstants.IIT_FOOTER_LINE_NUMBER; j++) {
				skipLinesIndexes2[j] = -(j + 1);
			}
			extractor.exceptLine(k, skipLinesIndexes2);
		}

		String text = extractPdfToText(extractor);
		return text;
	}
	
	public List<IITTran> parseIITTrans(String filePath, String pdfPassword) {
		List<IITTran> iitTrans = new ArrayList<>();
		
		String transText = parseTransToText(filePath, pdfPassword);
		if (StringUtils.isBlank(transText)) {
			return iitTrans;
		}
		
		List<List<String>> tranFieldsList = parseTransTextToTranFieldsList(transText);
		
		for (int i = 0; i < tranFieldsList.size(); i++) {
			if (StringUtils.isNotBlank(tranFieldsList.get(i).get(0))) {
				IITTran iitTran = new IITTran();
				iitTran.setDeclarationDate(tranFieldsList.get(i).get(0));
				iitTran.setPaidInOutAmount(tranFieldsList.get(i).get(1));
				iitTran.setStockInOutDate(tranFieldsList.get(i).get(2));
				iitTran.setIncomeItem(tranFieldsList.get(i).get(3));
				iitTran.setTaxPeriod(tranFieldsList.get(i).get(4));
				iitTran.setStockInTaxAuthority(formatStockInTaxAuthority(tranFieldsList.get(i).get(5)));
				if (tranFieldsList.get(i).size() == 7) {
					iitTran.setComment(tranFieldsList.get(i).get(6));
				} else {
					iitTran.setComment("");
				}
				iitTrans.add(iitTran);
			}
		}
		
		return iitTrans;
	}
	
	private String formatStockInTaxAuthority(String stockInTaxAuthority) {
		String formatStr = stockInTaxAuthority;
		
		try {
			//入库税务机关，一行最多显示12个汉字，超过12个就会换行，只有超过12个字才会需要调整
			//国成家都税管务理总委局员四会川税天务府局新区
			if (stockInTaxAuthority.length() <= 12 || stockInTaxAuthority.length() > 24) {
				return formatStr;
			} 
			
			// 下面就是显示两行的情况
			StringBuilder sb = new StringBuilder(stockInTaxAuthority);
			int charNumInNewLine = stockInTaxAuthority.length() - 12;
			for (int i = 0 ; i < charNumInNewLine; i++) {
				sb.append(stockInTaxAuthority.charAt(2 * i + 1));
			}
			for (int i = 1 ; i <= charNumInNewLine; i++) {
				sb.deleteCharAt(i);
			}
			formatStr = sb.toString();
		} catch (Exception e) {
			log.error("formatStockInTaxAuthority failed, stockInTaxAuthority: {}", stockInTaxAuthority, e);
			e.printStackTrace();
		}
			
		return formatStr;
	}


	public static void main(String[] args) throws IOException {
//		String pdfFilePath = "E:\\data\\file\\iit\\381859402262513295_d0ed1c34fda5a640698578392ced6a38_tax_nsjl-055614.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\381859402262513295_d0ed1c34fda5a640698578392ced6a38_tax_nsjl-055614.json";
//		String passWord = "055614";
//		String pdfFilePath = "E:\\data\\file\\iit\\381295244299215025_2f912da2c5dcbee03430d93b956f5961_tax_nsjl-272811.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\381295244299215025_2f912da2c5dcbee03430d93b956f5961_tax_nsjl-272811.json";
//		String passWord = "272811";

//		String pdfFilePath = "E:\\data\\file\\iit\\382006000938386319_01ffcc1ba1f9ac1aca08333f7f0aebb9_tax_nsjl-083661.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\382006000938386319_01ffcc1ba1f9ac1aca08333f7f0aebb9_tax_nsjl-083661.json";
//		String passWord = "083661";

//		String pdfFilePath = "E:\\data\\file\\iit\\382581175476031254_7bce4e73aa481a85a2e6865ba9b72661_tax_nsjl-224757.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\382581175476031254_7bce4e73aa481a85a2e6865ba9b72661_tax_nsjl-224757.json";
//		String passWord = "224757";
		
//		String pdfFilePath = "E:\\data\\file\\iit\\382127552405177999_a6783eef078e41bcc618a06cf70554aa_tax_nsjl-233231.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\382127552405177999_a6783eef078e41bcc618a06cf70554aa_tax_nsjl-233231.json";
//		String passWord = "233231";
		
//		String pdfFilePath = "E:\\data\\file\\iit\\382885884011218575_7e6cce107c8a4837011eec1f7628c438_tax_nsjl-145166.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\382885884011218575_7e6cce107c8a4837011eec1f7628c438_tax_nsjl-145166.json";
//		String passWord = "145166";
		
//		String pdfFilePath = "E:\\data\\file\\iit\\383307762106368911_ec2099b438809ee6962905e890c92518_tax_nsjl-161326.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\383307762106368911_ec2099b438809ee6962905e890c92518_tax_nsjl-161326.json";
//		String passWord = "161326";
		
//		String pdfFilePath = "E:\\data\\file\\iit\\389419489160077489_665ebefa2d85e02aae0e4c87bb68c272_tax_nsjl-151173.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\389419489160077489_665ebefa2d85e02aae0e4c87bb68c272_tax_nsjl-151173.json";
//		String passWord = "151173";
		
//		String pdfFilePath = "E:\\data\\file\\iit\\390268201054766735_d0c3e4dd44421a1981b597980fc28d1c_tax_nsjl-206994.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\390268201054766735_d0c3e4dd44421a1981b597980fc28d1c_tax_nsjl-206994.json";
//		String passWord = "206994";
		
		String pdfFilePath = "E:\\data\\file\\iit\\390282578038359695_abc79867a42191c9e419b1123e36b397_tax_nsjl-186014.pdf";
		String jsonFilePath = "E:\\data\\file\\iit\\390282578038359695_abc79867a42191c9e419b1123e36b397_tax_nsjl-186014.json";
		String passWord = "186014";
		
//		String pdfFilePath = "E:\\data\\file\\iit\\390268956247589775_0354870fe31ce8b3885841471e489de6_tax_nsjl-128116.pdf";
//		String jsonFilePath = "E:\\data\\file\\iit\\390268956247589775_0354870fe31ce8b3885841471e489de6_tax_nsjl-128116.json";
//		String passWord = "128116";

		File jsonFile = new File(jsonFilePath);
		IITPdfParser iitParser = new IITPdfParser();
		ResponseData<String> responseData = iitParser.parseIITPdfToJson(pdfFilePath, passWord);
		log.info(responseData.getData());
		FileUtils.write(jsonFile, responseData.getData(), EfpConstants.UTF_8);

		jsonFile.createNewFile();
		
//		log.info(iitParser.formatStockInTaxAuthority("国税家务税局务总局成都市⾦⽜区")); 
	}

}
